package com.amphiprion.prototype;

import android.app.Activity;
import android.os.Bundle;

import com.amphiprion.prototype.control.ControlerState;
import com.amphiprion.prototype.control.TouchControler;

public class GameActivity extends Activity {
	private volatile boolean running;
	private GameView view;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		view = new GameView(this);
		setContentView(view);

		final TouchControler tc = new TouchControler(view);

		new Thread(new Runnable() {

			@Override
			public void run() {
				running = true;
				long timer = System.currentTimeMillis();
				long drawtimer = System.currentTimeMillis();
				while (running) {
					if (!view.drawing) {
						ControlerState state = tc.getControlerState();
						long newtimer = System.currentTimeMillis();
						for (GameScreen scr : view.getScreens()) {
							scr.onInput(state, newtimer - timer);
						}
						timer = newtimer;
						if (newtimer - drawtimer >= 40) {
							drawtimer = newtimer;
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									view.invalidate();
								}
							});
						}
					}
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
					}
				}
			}
		}).start();
	}

	public void addScreen(GameScreen screen) {
		view.addScreen(screen);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		for (GameScreen scr : view.getScreens()) {
			scr.onDestroy();
		}
		super.onDestroy();
	}
}
